﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DGSFramework;
using System.Web.Security;
using System.IO;
using CodeCarvings.Piczard.Web;
using CodeCarvings.Piczard;
using System.Web.Services;
using System.Xml.Linq;
using CodeCarvings.Piczard.Filters.Watermarks;
using System.Web.Script.Services;

namespace Framework.WebmasterTool.Products
{
    public partial class ProductAdd : System.Web.UI.Page
    {
        DGSFrameworkEntities entity = new DGSFrameworkEntities();

        protected void Page_Load(object sender, EventArgs e)
        {
            //txtRealeaseDate.Attributes.Add("readonly", "readonly");
            //txtExpireDate.Attributes.Add("readonly", "readonly");
            siuImage.ImageRemove += new EventHandler(siuImage_ImageRemove);
            siuImage.ImageUpload += new SimpleImageUpload.ImageUploadEventHandler(siuImage_ImageUpload);
            if (!IsPostBack)
            {
                CheckPermission();
                CallCkeditors();
                //CleanImageUploadTemp();
                CallImageUpload();
                LoadCateDDL();
                LoadProductDetails();
            }
        }

        public void CheckPermission()
        {
            MembershipUser someUser = Membership.GetUser();
            if (someUser == null)
            {
                Response.Redirect(Globals.ApplicationPath + "LoginAdmin/Default.aspx");
            }
            bool flag = false;
            var user = entity.aspnet_Users.Where(us => us.UserName == someUser.UserName).FirstOrDefault();
            user.aspnet_Roles.Load();
            var rolesForUser = user.aspnet_Roles.ToList();
            foreach (var item in rolesForUser)
            {
                var permission = entity.udv_Permissions.Where(ps => ps.RoleId == item.RoleId).FirstOrDefault();
                if (permission.Product.Value == true)
                {
                    flag = true;
                }
            }
            if (flag == false)
            {
                lblPermissionMessage.Visible = true;
                Panel1.Visible = false;
            }
        }

        public void CallCkeditors()
        {
            Globals.CallCKFinder(txtDescription);
            Globals.CallCKFinder(txtDescription_en);
        }

        void siuImage_ImageRemove(object sender, EventArgs e)
        {
            chkWatermarkImage.Enabled = true;
        }

        void siuImage_ImageUpload(object sender, SimpleImageUpload.ImageUploadEventArgs args)
        {
            chkWatermarkImage.Enabled = false;
        }

        public void CleanImageUploadTemp()
        {
            foreach (var file in Directory.GetFiles(Server.MapPath(ConfigPaths.Path_ImageUploadTemp_Folder_MapPath)))
            {
                File.Delete(file);
            }
        }

        public void ImageUpload(SimpleImageUpload ctrImageUpload)
        {
            ctrImageUpload.ImageBackColorApplyMode = PictureTrimmerImageBackColorApplyMode.DoNotApply;
            ctrImageUpload.CropConstraint = new FreeCropConstraint();
            ctrImageUpload.PreviewFilter = new FixedResizeConstraint(200, 200, System.Drawing.Color.Black);
            ctrImageUpload.Text_BrowseButton = "Upload ảnh";
            ctrImageUpload.Text_CancelUploadButton = "Huỷ";
            ctrImageUpload.Text_EditButton = "Sửa ảnh";
            ctrImageUpload.Text_RemoveButton = "Xoá ảnh";
        }

        public void CallImageUpload()
        {
            ImageUpload(siuImage);
        }

        public void LoadCateDDL()
        {
            string levels = "|---";
            string spaces = "&nbsp;";
            List<udv_Categories> allCate = entity.udv_Categories.ToList();
            List<udv_Categories> cateBannerParent = allCate.Where(ca => ca.ParentID == ConfigPaths.Category_Product_ID).ToList();
            foreach (var item in cateBannerParent)
            {
                ddlCategories.Items.Add(new ListItem(item.Title, item.CateID.ToString()));
                LoadSubCateDDL(ref allCate, item.CateID, ref spaces, levels);
            }
        }

        public void LoadSubCateDDL(ref List<udv_Categories> allCate, int cateParentID, ref string spaces, string levels)
        {
            List<udv_Categories> subCateBanner = allCate.Where(ca => ca.ParentID == cateParentID).ToList();
            foreach (var item in subCateBanner)
            {
                ddlCategories.Items.Add(new ListItem(HttpUtility.HtmlDecode(spaces) + levels + item.Title, item.CateID.ToString()));
                if (entity.udv_Categories.Where(ca => ca.ParentID == item.CateID).ToList().Count > 0)
                {
                    spaces += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                    LoadSubCateDDL(ref allCate, item.CateID, ref spaces, levels);
                }
            }
            if (spaces.Length > 6)
                spaces = spaces.Substring(0, spaces.Length - 36);
        }

        public void LoadProductDetails()
        {
            if (Request.QueryString["ProductID"] != null)
            {
                int productID;
                int.TryParse(Request.QueryString["ProductID"], out productID);
                var productByID = entity.udv_Products.Include("udv_Categories").Where(pd => pd.ProductID == productID).FirstOrDefault();
                if (productByID != null)
                {
                    LoadListImageProduct(productByID.ProductID);
                    ddlCategories.SelectedValue = productByID.udv_Categories.CateID.ToString();
                    txtTitle.Text = productByID.Title.Trim();
                    txtTitle_en.Text = productByID.Title_en.Trim();
                    txtProductCode.Text = productByID.ProductCode.Trim();
                    txtManufacturer.Text = productByID.Manufacturer.Trim();
                    txtSize.Text = productByID.Size.Trim();
                    txtUnitInStock.Text = productByID.UnitInStock.HasValue == true ? productByID.UnitInStock.Value.ToString() : "0";
                    txtUnitPrice.Text = productByID.UnitPrice.HasValue == true ? String.Format("{0:0}", productByID.UnitPrice.Value) : "0";
                    txtSalePrice.Text = productByID.SalePrice.HasValue == true ? String.Format("{0:0}", productByID.SalePrice.Value) : "0";
                    txtPromotionPrice.Text = productByID.PromotionPrice.HasValue == true ? String.Format("{0:0}", productByID.PromotionPrice.Value) : "0";
                    txtPromotionPercent.Text = productByID.PromotionPercent.HasValue == true ? productByID.PromotionPercent.Value.ToString() : "0";
                    txtWarranty.Text = productByID.Warranty.HasValue == true ? productByID.Warranty.Value.ToString() : "0";
                    txtSummary.Text = productByID.Summary;
                    txtSummary_en.Text = productByID.Summary_en;
                    txtFeature.Text = productByID.Feature;
                    txtFeature_en.Text = productByID.Feature_en;
                    txtMetaDescription.Text = productByID.MetaDescription.Trim();
                    txtMetaKeywords.Text = productByID.MetaKeywords.Trim();
                    txtMetaTitle.Text = productByID.MetaTitle.Trim();
                    txtMetaOrther.Text = HttpUtility.HtmlDecode(productByID.MetaOrther.Trim());
                    if (productByID.ImageUrl != null && productByID.ImageUrl.Trim() != "")
                    {
                        string sourceImageFilePath = ConfigPaths.Path_ImageProduct_Folder_MapPath + productByID.ImageUrl;
                        siuImage.LoadImageFromFileSystem(Server.MapPath(sourceImageFilePath));
                        chkWatermarkImage.Enabled = false;
                    }
                    //load relate
                    txtRelateTop.Text = GetRelatesToString("top", productByID);
                    txtRelateBottom.Text = GetRelatesToString("bottom", productByID);
                    txtRelateProduct.Text = GetRelatesToString("product", productByID);
                    //load tag
                    productByID.udv_Tag.Load();
                    txtTags.Text = GetTagsToString(productByID.udv_Tag.ToList());

                    txtImageAlt.Text = productByID.ImageAlt.Trim();
                    txtDescription.Text = productByID.Description;
                    txtDescription_en.Text = productByID.Description_en;
                    txtDisplayOrder.Text = productByID.DisplayOrder.Value.ToString();
                    txtRealeaseDate.Text = String.Format("{0:dd/MM/yyyy hh:mm:ss tt}", productByID.ReleaseDate);
                    txtExpireDate.Text = String.Format("{0:dd/MM/yyyy hh:mm:ss tt}", productByID.ExpireDate);
                    chkCommentsEnable.Checked = productByID.CommentsEnabled.Value;
                    chkApprovedComments.Checked = productByID.ApprovedComments.Value;
                    chkRatingFix.Checked = productByID.FixRating.Value;
                    txtRating.Text = productByID.Rating.Value.ToString();
                    chkActiveInMenu.Checked = productByID.ActiveInMenu.Value;
                    chkOnlyForMember.Checked = productByID.OnlyForMembers.Value;
                    chkIsActive.Checked = productByID.IsActive.Value;
                    chkTopNews.Checked = productByID.StatusID == 1 ? true : false;
                    lblAddedDate.Text = String.Format("{0:dd/MM/yyyy HH:mm:ss tt}", productByID.AddedDate);
                    lblAddedBy.Text = productByID.AddedBy;
                    lblUpdatedDate.Text = String.Format("{0:dd/MM/yyyy HH:mm:ss tt}", productByID.UpdatedDate);
                    lblUpdatedBy.Text = productByID.UpdatedBy;
                    lblTotalRating.Text = productByID.TotalRating.ToString();
                    lblTotalViews.Text = productByID.TotalViews.ToString();
                    lbllink.Text = ConfigPaths.Domain_Url + productByID.UrlRewrite + DGSFramework.Globals.GetUrlRewriteExtension();
                }
                else
                {
                    Response.Redirect("Default.aspx");
                }
            }
        }

        public void LoadListImageProduct(int productID)
        {
            List<udv_ProductImages> listImageProduct = entity.udv_ProductImages.Where(ip => ip.udv_Products.ProductID == productID).ToList();
            dtlImage.DataSource = listImageProduct;
            dtlImage.DataBind();
        }

        [WebMethod]
        public static void DeleteImageProduct(string ImageID)
        {
            DGSFrameworkEntities entity = new DGSFrameworkEntities();
            int imageID = int.Parse(ImageID);
            udv_ProductImages imageProduct = entity.udv_ProductImages.Where(ip => ip.ImageID == imageID).FirstOrDefault();
            if (imageProduct != null)
            {
                Globals.DelelteFile(HttpContext.Current.Server.MapPath(ConfigPaths.Path_ImageProduct_Folder_MapPath + imageProduct.ImageUrl));
                entity.DeleteObject(imageProduct);
                entity.SaveChanges();
            }
        }

        [WebMethod]
        public static void EditAttributeImageProduct(string ImageID, string NewValue, string Attribute)
        {
            DGSFrameworkEntities entity = new DGSFrameworkEntities();
            int imageID = int.Parse(ImageID);
            udv_ProductImages imageProduct = entity.udv_ProductImages.Where(ip => ip.ImageID == imageID).FirstOrDefault();
            string value = NewValue;
            string attribute = Attribute;
            if (imageProduct != null)
            {
                if (attribute.Trim() == "title")
                {
                    imageProduct.Title = value;
                }
                else if (attribute.Trim() == "title_en")
                {
                    imageProduct.Title_en = value;
                }
                else if (attribute.Trim() == "alt")
                {
                    imageProduct.ImageAlt = value;
                }
                entity.SaveChanges();
            }
        }

        protected void chkWatermarkImage_CheckedChanged(object sender, EventArgs e)
        {
            if (chkWatermarkImage.Checked == true && siuImage.HasImage == false)
            {
                XDocument xDocWatermark = XDocument.Load(Server.MapPath(ConfigPaths.Path_Watermark_Xml));
                XElement xEImage = xDocWatermark.Descendants("img").FirstOrDefault();
                siuImage.PostProcessingFilter = new ImageWatermark(Server.MapPath(ConfigPaths.Path_ImageUpload_Folder_MapPath + xEImage.Value), System.Drawing.ContentAlignment.BottomRight);
            }
            else if (chkWatermarkImage.Checked == false && siuImage.HasImage == false)
            {
                siuImage.PostProcessingFilter = null;
            }
        }

        public List<string> UploadAndGetImageName()
        {
            List<string> strFileName = new List<string>();
            HttpFileCollection hfc = Request.Files;
            if (hfc.Count > 0)
            {
                for (int i = 0; i < hfc.Count; i++)
                {
                    HttpPostedFile hpf = hfc[i];
                    if (hpf.FileName.Trim() != "")
                    {
                        string strFileNameTemp = Globals.GetFileName(hpf.FileName);
                        strFileName.Add(strFileNameTemp);
                        if (chkWatermarkImage2.Checked == false)
                            hpf.SaveAs(Server.MapPath(ConfigPaths.Path_ImageProduct_Folder_MapPath + strFileNameTemp));
                        else
                        {
                            XDocument xDocWatermark = XDocument.Load(Server.MapPath(ConfigPaths.Path_Watermark_Xml));
                            XElement xEImage = xDocWatermark.Descendants("img").FirstOrDefault();
                            Globals.CreateWatermark(hpf, Server.MapPath(ConfigPaths.Path_ImageProduct_Folder_MapPath + strFileNameTemp), Server.MapPath(ConfigPaths.Path_ImageUpload_Folder_MapPath + xEImage.Value));
                        }
                    }
                }
            }
            return strFileName;
        }

        public List<string> GetImageTitle()
        {
            List<string> listTitle = new List<string>();
            for (int i = 0; i < int.Parse(hdfNumImage.Value); i++)
            {
                if (Request.Form["Title" + i.ToString()] != null)
                {
                    listTitle.Add(Request.Form["Title" + i.ToString()].Trim());
                }
            }
            return listTitle;
        }

        public List<string> GetImageTitle_en()
        {
            List<string> listTitle = new List<string>();
            for (int i = 0; i < int.Parse(hdfNumImage.Value); i++)
            {
                if (Request.Form["Title_en" + i.ToString()] != null)
                {
                    listTitle.Add(Request.Form["Title_en" + i.ToString()].Trim());
                }
            }
            return listTitle;
        }

        public List<string> GetImageAlt()
        {
            List<string> listAlt = new List<string>();
            for (int i = 0; i < int.Parse(hdfNumImage.Value); i++)
            {
                if (Request.Form["Alt" + i.ToString()] != null)
                {
                    listAlt.Add(Request.Form["Alt" + i.ToString()].Trim());
                }
            }
            return listAlt;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            int cateID = 0;
            try
            {
                cateID = int.Parse(ddlCategories.SelectedValue);
            }
            catch
            {
                lblMsg.Text = "Chưa chọn danh mục cho sản phẩm";
            }
            udv_Categories cateForProduct = entity.udv_Categories.Where(ca => ca.CateID == cateID).FirstOrDefault();
            int countChildCate = entity.udv_Categories.Where(ca => ca.ParentID == cateID).ToList().Count;
            if (countChildCate > 0)
            {
                lblMsg.Text = "Danh mục này có danh mục con nên không thể có sản phẩm";
                lblMsg.ForeColor = System.Drawing.Color.Red;
                return;
            }
            List<string> listImageNameUpload = UploadAndGetImageName();
            List<string> listImageTitle = new List<string>();
            //List<string> listImageTitle_en = new List<string>();
            List<string> listImageAlt = new List<string>();
            if (listImageNameUpload.Count > 0)
            {
                listImageTitle = GetImageTitle();
                //listImageTitle_en = GetImageTitle_en();
                listImageAlt = GetImageAlt();
            }
            if (Request.QueryString["ProductID"] == null)
            {
                udv_Products productInsert = new udv_Products();
                productInsert.udv_Categories = cateForProduct;
                productInsert.Title = txtTitle.Text.Trim();
                productInsert.Title_en = txtTitle_en.Text.Trim();
                productInsert.ProductCode = txtProductCode.Text.Trim();
                productInsert.Manufacturer = txtManufacturer.Text.Trim();
                productInsert.Size = txtSize.Text.Trim();
                productInsert.UnitInStock = txtUnitInStock.Text.Trim() != "" ? int.Parse(txtUnitInStock.Text.Trim()) : 0;
                productInsert.UnitPrice = txtUnitPrice.Text.Trim() != "" ? decimal.Parse(txtUnitPrice.Text.Trim()) : 0;
                productInsert.SalePrice = txtSalePrice.Text.Trim() != "" ? decimal.Parse(txtSalePrice.Text.Trim()) : 0;
                productInsert.PromotionPrice = txtPromotionPrice.Text.Trim() != "" ? decimal.Parse(txtPromotionPrice.Text.Trim()) : 0;
                productInsert.PromotionPercent = txtPromotionPercent.Text.Trim() != "" ? int.Parse(txtPromotionPercent.Text.Trim()) : 0;
                productInsert.Warranty = txtWarranty.Text.Trim() != "" ? int.Parse(txtWarranty.Text.Trim()) : 0;
                productInsert.Summary = txtSummary.Text;
                productInsert.Summary_en = txtSummary_en.Text;
                productInsert.Feature = txtFeature.Text;
                productInsert.Feature_en = txtFeature_en.Text;
                productInsert.MetaDescription = txtMetaDescription.Text.Trim();
                productInsert.MetaKeywords = txtMetaKeywords.Text.Trim();
                productInsert.MetaTitle = txtMetaTitle.Text.Trim();
                productInsert.MetaOrther = HttpUtility.HtmlEncode(txtMetaOrther.Text.Trim());
                if (siuImage.HasImage == true)
                {
                    string fileNameImage = Globals.GetFileName(siuImage.SourceImageClientFileName);
                    siuImage.SaveProcessedImageToFileSystem(ConfigPaths.Path_ImageProduct_Folder + fileNameImage);
                    productInsert.ImageUrl = fileNameImage;
                }
                else
                {
                    productInsert.ImageUrl = "";
                }
                productInsert.ImageAlt = txtImageAlt.Text.Trim();
                productInsert.Description = txtDescription.Text;
                productInsert.Description_en = txtDescription_en.Text;
                productInsert.DisplayOrder = int.Parse(txtDisplayOrder.Text);
                if (txtRealeaseDate.Text.Trim() != "")
                {
                    productInsert.ReleaseDate = DateTime.ParseExact(txtRealeaseDate.Text.Trim(), "dd/MM/yyyy hh:mm:ss tt", null);
                }
                if (txtExpireDate.Text.Trim() != "")
                {
                    productInsert.ExpireDate = DateTime.ParseExact(txtExpireDate.Text.Trim(), "dd/MM/yyyy hh:mm:ss tt", null);
                }
                productInsert.CommentsEnabled = chkCommentsEnable.Checked;
                productInsert.ApprovedComments = chkApprovedComments.Checked;
                productInsert.FixRating = chkRatingFix.Checked;
                productInsert.Rating = float.Parse(txtRating.Text);
                productInsert.ActiveInMenu = chkActiveInMenu.Checked;
                productInsert.OnlyForMembers = chkOnlyForMember.Checked;
                productInsert.IsActive = chkIsActive.Checked;
                productInsert.StatusID = chkTopNews.Checked == true ? 1 : 0;
                productInsert.TotalRating = 0;
                productInsert.TotalViews = 0;
                productInsert.AddedDate = DateTime.Now;
                productInsert.AddedBy = Membership.GetUser().UserName;
                productInsert.UpdatedDate = DateTime.Now;
                productInsert.UpdatedBy = Membership.GetUser().UserName;
                entity.AddToudv_Products(productInsert);
                entity.SaveChanges();
                // add relate to article
                AddRelateToProduct(txtRelateTop.Text, productInsert, "top");
                AddRelateToProduct(txtRelateBottom.Text, productInsert, "bottom");
                AddRelateToProduct(txtRelateProduct.Text, productInsert, "product");
                // add tag to article
                AddTagToProduct(txtTags.Text, productInsert);
                if (listImageNameUpload.Count > 0)
                {
                    for (int i = 0; i < listImageNameUpload.Count; i++)
                    {
                        udv_ProductImages imageProduct = new udv_ProductImages();
                        imageProduct.udv_Products = productInsert;
                        imageProduct.ImageUrl = listImageNameUpload[i];
                        imageProduct.ImageAlt = listImageAlt[i];
                        imageProduct.Title = listImageTitle[i];
                        //imageProduct.Title_en = listImageTitle_en[i];
                        imageProduct.Description = "";
                        imageProduct.Description_en = "";
                        imageProduct.AddedDate = DateTime.Now;
                        entity.AddToudv_ProductImages(imageProduct);
                        entity.SaveChanges();
                    }
                }
                string urlRewriteProduct = Globals.CreateUrlRewriteProduct(ref entity, productInsert.ProductID, true);
                productInsert.UrlRewrite = urlRewriteProduct;
                entity.SaveChanges();
                Globals.CreateROR("~/ror.xml", urlRewriteProduct + DGSFramework.Globals.GetUrlRewriteExtension(), productInsert.Title, productInsert.MetaDescription);
                Globals.CreateSiteMap("~/sitemap.xml", urlRewriteProduct + DGSFramework.Globals.GetUrlRewriteExtension());
                Globals.CreateUrlList("~/urllist.txt", urlRewriteProduct + DGSFramework.Globals.GetUrlRewriteExtension());

                //create db log
                productInsert.udv_CategoriesReference.Load();
                CreateDBLog(productInsert.ProductID, productInsert.udv_Categories.CateID, TypeAction.Insert, "Tạo bài viết sản phẩm: " + productInsert.Title, productInsert.Summary, productInsert.Description, productInsert.ReleaseDate != null ? string.Format("{0:dd/MM/yyyy} HH:mm:ss", productInsert.ReleaseDate) : "",
                    productInsert.ExpireDate != null ? string.Format("{0:dd/MM/yyyy} HH:mm:ss", productInsert.ExpireDate) : "", productInsert.IsActive.Value.ToString(), productInsert.StatusID.Value.ToString(), productInsert.MetaDescription, productInsert.MetaKeywords);

                //data cache
                Cache.Remove("Product");
                //clear outputcache
                HttpResponse.RemoveOutputCacheItem("/Default.aspx");
                HttpResponse.RemoveOutputCacheItem("/Products.aspx");
                //redirect page
                Response.Redirect("Default.aspx");
            }
            else
            {
                int productID;
                int.TryParse(Request.QueryString["ProductID"].ToString(), out productID);
                udv_Products productUpdate = entity.udv_Products.Where(pd => pd.ProductID == productID).FirstOrDefault();
                if (productUpdate != null)
                {
                    string urlRewriteProductOld = Globals.CreateUrlRewriteProduct(ref entity, productUpdate.ProductID, true);
                    string urlRewriteProductNew;
                    productUpdate.udv_Categories = cateForProduct;
                    string oldTitle = productUpdate.Title;
                    productUpdate.Title = txtTitle.Text.Trim();
                    productUpdate.Title_en = txtTitle_en.Text.Trim();
                    productUpdate.ProductCode = txtProductCode.Text.Trim();
                    productUpdate.Manufacturer = txtManufacturer.Text.Trim();
                    productUpdate.Size = txtSize.Text.Trim();
                    productUpdate.UnitInStock = txtUnitInStock.Text.Trim() != "" ? int.Parse(txtUnitInStock.Text.Trim()) : 0;
                    productUpdate.UnitPrice = txtUnitPrice.Text.Trim() != "" ? decimal.Parse(txtUnitPrice.Text.Trim()) : 0;
                    productUpdate.SalePrice = txtSalePrice.Text.Trim() != "" ? decimal.Parse(txtSalePrice.Text.Trim()) : 0;
                    productUpdate.PromotionPrice = txtPromotionPrice.Text.Trim() != "" ? decimal.Parse(txtPromotionPrice.Text.Trim()) : 0;
                    productUpdate.PromotionPercent = txtPromotionPercent.Text.Trim() != "" ? int.Parse(txtPromotionPercent.Text.Trim()) : 0;
                    productUpdate.Warranty = txtWarranty.Text.Trim() != "" ? int.Parse(txtWarranty.Text.Trim()) : 0;
                    productUpdate.Summary = txtSummary.Text;
                    productUpdate.Summary_en = txtSummary_en.Text;
                    productUpdate.Feature = txtFeature.Text;
                    productUpdate.Feature_en = txtFeature_en.Text;
                    productUpdate.MetaDescription = txtMetaDescription.Text.Trim();
                    productUpdate.MetaKeywords = txtMetaKeywords.Text.Trim();
                    productUpdate.MetaTitle = txtMetaTitle.Text.Trim();
                    productUpdate.MetaOrther = HttpUtility.HtmlEncode(txtMetaOrther.Text.Trim());
                    if (siuImage.HasNewImage == true)
                    {
                        Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_ImageProduct_Folder_MapPath + productUpdate.ImageUrl));
                        string fileNameImage = Globals.GetFileName(siuImage.SourceImageClientFileName);
                        siuImage.SaveProcessedImageToFileSystem(ConfigPaths.Path_ImageProduct_Folder + fileNameImage);
                        productUpdate.ImageUrl = fileNameImage;
                    }
                    else if (siuImage.HasImage == false)
                    {
                        Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_ImageProduct_Folder_MapPath + productUpdate.ImageUrl));
                        productUpdate.ImageUrl = "";
                    }
                    productUpdate.ImageAlt = txtImageAlt.Text.Trim();
                    productUpdate.Description = txtDescription.Text;
                    productUpdate.Description_en = txtDescription_en.Text;
                    productUpdate.DisplayOrder = int.Parse(txtDisplayOrder.Text);
                    if (txtRealeaseDate.Text.Trim() != "")
                    {
                        productUpdate.ReleaseDate = DateTime.ParseExact(txtRealeaseDate.Text.Trim(), "dd/MM/yyyy hh:mm:ss tt", null);
                    }
                    else
                    {
                        productUpdate.ReleaseDate = null;
                    }
                    if (txtExpireDate.Text.Trim() != "")
                    {
                        productUpdate.ExpireDate = DateTime.ParseExact(txtExpireDate.Text.Trim(), "dd/MM/yyyy hh:mm:ss tt", null);
                    }
                    else
                    {
                        productUpdate.ExpireDate = null;
                    }
                    productUpdate.CommentsEnabled = chkCommentsEnable.Checked;
                    productUpdate.ApprovedComments = chkApprovedComments.Checked;
                    productUpdate.FixRating = chkRatingFix.Checked;
                    productUpdate.Rating = float.Parse(txtRating.Text);
                    productUpdate.ActiveInMenu = chkActiveInMenu.Checked;
                    productUpdate.OnlyForMembers = chkOnlyForMember.Checked;
                    productUpdate.IsActive = chkIsActive.Checked;
                    productUpdate.StatusID = chkTopNews.Checked == true ? 1 : 0;
                    productUpdate.UpdatedDate = DateTime.Now;
                    productUpdate.UpdatedBy = Membership.GetUser().UserName;
                    entity.SaveChanges();
                    // add tag to article
                    AddRelateToProduct(txtRelateTop.Text, productUpdate, "top");
                    AddRelateToProduct(txtRelateBottom.Text, productUpdate, "bottom");
                    AddRelateToProduct(txtRelateProduct.Text, productUpdate, "product");
                    // add tag to article
                    AddTagToProduct(txtTags.Text, productUpdate);
                    if (listImageNameUpload.Count > 0)
                    {
                        for (int i = 0; i < listImageNameUpload.Count; i++)
                        {
                            udv_ProductImages imageProduct = new udv_ProductImages();
                            imageProduct.udv_Products = productUpdate;
                            imageProduct.ImageUrl = listImageNameUpload[i];
                            imageProduct.ImageAlt = listImageAlt[i];
                            imageProduct.Title = listImageTitle[i];
                            //imageProduct.Title_en = listImageTitle_en[i];
                            imageProduct.Description = "";
                            imageProduct.Description_en = "";
                            imageProduct.AddedDate = DateTime.Now;
                            entity.AddToudv_ProductImages(imageProduct);
                            entity.SaveChanges();
                        }
                    }
                    urlRewriteProductNew = Globals.CreateUrlRewriteProduct(ref entity, productUpdate.ProductID, true);
                    productUpdate.UrlRewrite = urlRewriteProductNew;
                    entity.SaveChanges();
                    Globals.UpdateROR("~/ror.xml", urlRewriteProductOld + DGSFramework.Globals.GetUrlRewriteExtension(), urlRewriteProductNew + DGSFramework.Globals.GetUrlRewriteExtension(), productUpdate.Title, productUpdate.MetaDescription);
                    Globals.UpdateSiteMap("~/sitemap.xml", urlRewriteProductOld + DGSFramework.Globals.GetUrlRewriteExtension(), urlRewriteProductNew + DGSFramework.Globals.GetUrlRewriteExtension());
                    Globals.UpdateUrlList("~/urllist.txt", urlRewriteProductOld + DGSFramework.Globals.GetUrlRewriteExtension(), urlRewriteProductNew + DGSFramework.Globals.GetUrlRewriteExtension());

                    //create db log
                    CreateDBLog(productUpdate.ProductID, productUpdate.udv_Categories.CateID, TypeAction.Update, "Cập nhật bài viết sản phẩm: " + oldTitle + " - " + productUpdate.Title, productUpdate.Summary, productUpdate.Description, productUpdate.ReleaseDate != null ? string.Format("{0:dd/MM/yyyy} HH:mm:ss", productUpdate.ReleaseDate) : "",
                        productUpdate.ExpireDate != null ? string.Format("{0:dd/MM/yyyy} HH:mm:ss", productUpdate.ExpireDate) : "", productUpdate.IsActive.Value.ToString(), productUpdate.StatusID.Value.ToString(), productUpdate.MetaDescription, productUpdate.MetaKeywords);

                    //data cache
                    Cache.Remove("Product");
                    //output cache
                    string key = "/ProductDetails.aspx?ProductID=" + productUpdate.ProductID.ToString();
                    Cache.Remove(key);
                    HttpResponse.RemoveOutputCacheItem("/Default.aspx");
                    HttpResponse.RemoveOutputCacheItem("/Products.aspx");
                    //redirect page
                    Response.Redirect("Default.aspx");
                }
                else
                {
                    lblMsg.Text = "Sản phẩm muốn cập nhật không tồn tại";
                    lblMsg.ForeColor = System.Drawing.Color.Red;
                }
            }
        }

        public List<string> ParseRelatesString(string relateString)
        {
            return relateString.Split('~').Select(tg => tg.ToLower().Trim()).Distinct().ToList();
        }

        public string GetRelatesToString(string position, udv_Products product)
        {
            product.udv_Relate.Load();
            var relateNames = product.udv_Relate.Where(tg => tg.Position.ToLower().Trim() == position.ToLower().Trim()).Select(tg => tg.RelateName);
            return string.Join("~ ", relateNames.ToArray());
        }

        public List<udv_Relate> FindRelatesAddedArticleByNames(List<string> relateNames, string position)
        {
            List<udv_Relate> existingRelates = entity.udv_Relate.ToList().Where(tg => relateNames.Any(tn => tg.RelateName == tn)).ToList();
            foreach (var item in relateNames)
            {
                if (!existingRelates.Any(tg => tg.RelateName == item))
                {
                    int? postID = entity.udv_Articles.Where(ar => ar.Title.ToLower().Trim() == item.ToLower().Trim()).Select(ar => ar.ArticleID).FirstOrDefault();
                    if (postID != null && postID != 0)
                    {
                        udv_Relate newRelate = new udv_Relate { RelateName = item, PostID = postID, Position = position };
                        entity.AddToudv_Relate(newRelate);
                        entity.SaveChanges();
                        existingRelates.Add(newRelate);
                    }
                    else
                    {
                        postID = entity.udv_Products.Where(ar => ar.Title.ToLower().Trim() == item.ToLower().Trim()).Select(ar => ar.ProductID).FirstOrDefault();
                        if (postID != null)
                        {
                            udv_Relate newRelate = new udv_Relate { RelateName = item, PostID = postID, Position = position };
                            entity.AddToudv_Relate(newRelate);
                            entity.SaveChanges();
                            existingRelates.Add(newRelate);
                        }
                    }
                }
            }
            return existingRelates;
        }

        public void AddRelateToProduct(string relateString, udv_Products product, string position)
        {
            relateString = relateString.Replace("\r\n", "").Replace("\n", "").Replace("\r", "");
            product.udv_Relate.Load();
            product.udv_Relate
                .Where(tg => tg.Position.ToLower().Trim() == position.ToLower().Trim()).ToList()
                .ForEach(tg => entity.DeleteObject(tg));
            entity.SaveChanges();
            List<udv_Relate> relates = string.IsNullOrEmpty(relateString) ? null : FindRelatesAddedArticleByNames(ParseRelatesString(relateString), position);
            if (relates != null && relates.Count != 0)
            {
                relates.ForEach(tg => product.udv_Relate.Add(tg));
            }
            entity.SaveChanges();
        }

        [WebMethodAttribute(), ScriptMethodAttribute()]
        public static string[] GetCompletionTagList(string prefixText, int count, string contextKey)
        {
            DGSFrameworkEntities entity = new DGSFrameworkEntities();
            var listTags = entity.udv_Tag.ToList();
            return (from tg in listTags where tg.TagName.Contains(prefixText) select tg.TagName).Take(count).ToArray();
        }

        public List<string> ParseTagsString(string tagString)
        {
            return tagString.Split(',').Select(tg => tg.ToLower().Trim()).Distinct().ToList();
        }

        public string GetTagsToString(List<udv_Tag> tags)
        {
            var tagNames = tags.Select(tg => tg.TagName);
            return string.Join(", ", tagNames.ToArray());
        }

        public List<udv_Tag> FindTagsAddByNames(List<string> tagNames)
        {
            List<udv_Tag> alltag = entity.udv_Tag.ToList();
            List<udv_Tag> existingTags = alltag.Where(tg => tagNames.Any(tn => tg.TagName == tn)).ToList();
            foreach (var item in tagNames)
            {
                if (!existingTags.Any(tg => tg.TagName == item))
                {
                    udv_Tag newTag = new udv_Tag { TagName = item };
                    entity.AddToudv_Tag(newTag);
                    entity.SaveChanges();
                    existingTags.Add(newTag);
                }
            }
            return existingTags;
        }

        public void AddTagToProduct(string tagString, udv_Products product)
        {
            product.udv_Tag.Load();
            product.udv_Tag.Clear();
            entity.SaveChanges();
            List<udv_Tag> tags = string.IsNullOrEmpty(tagString) ? null : FindTagsAddByNames(ParseTagsString(tagString));
            if (tags != null && tags.Count != 0)
            {
                tags.ForEach(tg => product.udv_Tag.Add(tg));
            }
            entity.SaveChanges();
        }

        public void CreateDBLog(int? postID, int? postCateID, TypeAction typeAction, string title, string _abstract, string description,
        string releaseDate, string expireDate, string isApproved, string statusID, string metaDescription, string metaKeywords)
        {
            udv_Log log = new udv_Log();
            log.PostID = postID;
            log.PostCateID = postCateID;
            log.TypeAction = (int)typeAction;
            log.Title = title;
            log.Abstract = _abstract;
            log.Description = description;
            log.ReleaseDate = releaseDate;
            log.ExpireDate = expireDate;
            log.IsApproved = isApproved;
            log.StatusID = statusID;
            log.MetaDescription = metaDescription;
            log.MetaKeywords = metaKeywords;
            log.ActionedDate = DateTime.Now;
            log.ActionBy = Membership.GetUser().UserName;
            log.IpAdress = Globals.GetClientIPAddress();

            entity.AddToudv_Log(log);
            entity.SaveChanges();
        }
    }
}